<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="水域类型" prop="waterType">
        <el-select v-model="queryParams.waterType" placeholder="请输入水域类型" clearable>
          <el-option v-for="dict in dict.type.watertype" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>


      <el-form-item label="水域名称" prop="waterName">
        <el-input v-model="queryParams.waterName" placeholder="请输入水域名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="位置名" prop="locationName">
        <el-input v-model="queryParams.locationName" placeholder="请输入位置名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>


      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="crateTime">
        <el-date-picker clearable v-model="queryParams.crateTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['map:water:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['map:water:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['map:water:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['map:water:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="waterList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="水域类型" align="center" prop="waterType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.watertype" :value="scope.row.waterType"/>
        </template>
      </el-table-column>
      <el-table-column label="水域名称" align="center" prop="waterName" />
      <el-table-column label="位置名" align="center" prop="locationName" />
      <el-table-column label="经度" align="center" prop="longitude" />
      <el-table-column label="纬度" align="center" prop="latitude" />
      <el-table-column label="捕获总数" align="center" prop="catchTotal" />
      <el-table-column label="单次钓价" align="center" prop="price" />
      <el-table-column label="是否禁止钓鱼" align="center" prop="useStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.useStatus" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>



      <el-table-column label="创建时间" align="center" prop="crateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.crateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['map:water:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['map:water:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改水域管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-row>
          <el-col :span="12">
            <el-form-item label="水域名称" prop="waterName">
              <el-input v-model="form.waterName" placeholder="请输入水域名称" />
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="水域图片" prop="image">
              <image-upload v-model="form.image" :limit="limit" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="水域类型" prop="waterType">
              <el-select v-model="form.waterType" placeholder="请输入水域类型">
                <el-option v-for="dict in dict.type.watertype" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="保护鱼种" prop="protectingFishids">
              <el-select v-model="form.protectingFishids" placeholder="请选择保护鱼种" filterable multiple clearable
                size="small">
                <el-option v-for="dict in fishtypeList" :key="dict.id" :label="dict.fishType" :value="dict.id" />
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="钓鱼区域" prop="fishingZone">
              <el-input v-model="form.fishingZone" readonly @click.native="openMapDialog" placeholder="请输入钓鱼区域" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
<el-form-item label="位置名" prop="locationName">
            <el-input type="textarea" :rows="2" v-model="form.locationName" placeholder="请输入位置名" />
          </el-form-item>


          </el-col>
        </el-row>

        <el-row>

          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="form.longitude" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="form.latitude" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="禁钓区域" prop="noFishingZone">
              <el-input v-model="form.noFishingZone" readonly @click.native="openNoFishingMapDialog"
                placeholder="请输入禁止钓鱼区域" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法律法规" prop="lawsRegulations">
              <el-input type="textarea" :rows="2" v-model="form.lawsRegulations" placeholder="请输入法律法规" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="捕获总数" prop="catchTotal">
              <el-input v-model="form.catchTotal" placeholder="请输入捕获总数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单次钓价" prop="price">
              <el-input v-model="form.price" placeholder="请输入单次钓价" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="禁止钓鱼" prop="useStatus">
              <el-radio-group v-model="form.useStatus">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value"
                  :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value"
                  :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="12">
            <el-form-item label="开启预测" prop="isopen">
              <el-radio-group v-model="form.isopen">
                <el-radio v-for="dict in dict.type.sys_isopen" :key="dict.value"
                  :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据" prop="	catchredata">
                <el-input v-model="form.catchredata" type="textarea" :rows="2" placeholder="请输入24小时数据" /><span class="el-form-item__description" style="color: #909399; font-size: 12px; margin-top: 5px;">请输入24个整数数据，用逗号分隔，例如：1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 腾讯地图选择对话框 -->
    <el-dialog title="选择钓鱼区域" :visible.sync="mapDialogVisible" width="80%" append-to-body>
      <div id="map-container" style="height: 500px;"></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmMapSelection">确 定</el-button>
        <el-button @click="mapDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 禁钓区域地图选择对话框 -->
    <el-dialog title="选择禁钓区域" :visible.sync="noFishingMapDialogVisible" width="80%" append-to-body>
      <div id="no-fishing-map-container" style="height: 500px;"></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmNoFishingMapSelection">确 定</el-button>
        <el-button @click="noFishingMapDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listWater,
    getWater,
    delWater,
    addWater,
    updateWater
  } from "@/api/map/water";
  import {
    listFishtype,
    getFishtype,
    delFishtype,
    addFishtype,
    updateFishtype
  } from "@/api/map/fishtype";
  export default {
    name: "Water",
    dicts: ['sys_normal_disable', 'watertype','sys_isopen'],
    data() {
      return {
        noFishingMapDialogVisible: false,
        noFishingMap: null,
        noFishingDrawingManager: null,
        noFishingSelectedOverlay: null,
        mapDialogVisible: false,
        map: null,
        drawingManager: null,
        selectedOverlay: null,
        limit: 1,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 水域管理表格数据
        waterList: [],
        // 弹出层标题
        title: "",
        fishtypeList: {},
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          waterType: null,
          waterName: null,
          locationName: null,
          longitude: null,
          latitude: null,
          catchTotal: null,
          price: null,
          useStatus: null,
          status: null,
          crateTime: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          waterName: [
            {required: true, message: "水域名称不能为空", trigger: "blur"}
          ],
          image: [
            {required: true, message: "图片不能为空", trigger: "blur"}
          ],
          waterType: [
            {required: true, message: "水域类型不能为空", trigger: "blur"}
          ],
          protectingFishids: [
            {required: true, message: "保护鱼种不能为空", trigger: "blur"}
          ],
          locationName: [
            {required: true, message: "位置名不能为空", trigger: "blur"}
          ],
          longitude: [
            {required: true, message: "经度不能为空", trigger: "blur"}
          ],
          latitude: [
            {required: true, message: "纬度不能为空", trigger: "blur"}
          ],
          catchredata: [
            {required: true, message: "24小时数据不能为空", trigger: "blur"},
            {
              validator: (rule, value, callback) => {
                if (value) {
                  const dataArray = value.split(',');
                  if (dataArray.length !== 24) {
                    callback(new Error('请输入24个数据点，用逗号分隔'));
                    return;
                  }
                  
                  // 验证所有数据都是整数
                  for (let i = 0; i < dataArray.length; i++) {
                    const num = dataArray[i].trim();
                    if (!/^\d+$/.test(num)) {
                      callback(new Error(`第${i+1}个数据必须是整数`));
                      return;
                    }
                  }
                  callback();
                } else {
                  callback();
                }
              },
              trigger: 'blur'
            }
          ]
        }
      };
    },
    created() {
      this.getList();
      var isbprr = this.queryParams;
      isbprr.pageSize = 100;
      listFishtype(isbprr).then(response => {
        this.fishtypeList = response.rows;
      });

    },
    methods: {
      async openNoFishingMapDialog() {
        try {
          // 先加载地图API
          await this.loadTencentMap();

          // 确保API加载完成后再显示对话框
          this.noFishingMapDialogVisible = true;

          // 等待DOM更新完成
          await this.$nextTick();

          // 初始化地图
          const mapContainer = document.getElementById('no-fishing-map-container');
          if (!mapContainer) {
            throw new Error('找不到地图容器');
          }

          // 确保地图实例被正确创建
          if (!this.noFishingMap && window.qq && window.qq.maps) {
            const center = new window.qq.maps.LatLng(39.916527, 116.397128);
            this.noFishingMap = new window.qq.maps.Map(mapContainer, {
              center: center,
              zoom: 12,
              mapTypeControl: true
            });

            // 初始化绘制工具
            this.noFishingDrawingManager = new window.qq.maps.drawing.DrawingManager({
              map: this.noFishingMap,
              drawingMode: window.qq.maps.drawing.OverlayType.POLYGON,
              drawingControl: true,
              drawingControlOptions: {
                position: window.qq.maps.ControlPosition.TOP_CENTER,
                drawingModes: [window.qq.maps.drawing.OverlayType.POLYGON]
              }
            });

            // 监听绘制完成事件
            window.qq.maps.event.addListener(this.noFishingDrawingManager, 'overlaycomplete', (event) => {
              if (this.noFishingSelectedOverlay) {
                this.noFishingSelectedOverlay.setMap(null);
              }
              this.noFishingSelectedOverlay = event.overlay;
              this.calculateNoFishingAreaInfo();
            });
          }

          // 触发地图重绘
          if (this.noFishingMap) {
            this.$nextTick(() => {
              this.noFishingMap.panTo(this.noFishingMap.getCenter());
            });
          }

        } catch (error) {
          console.error('禁钓区域地图初始化失败:', error);
          this.$message.error('地图加载失败，请重试');
          this.noFishingMapDialogVisible = false;
        }
      },

      // 计算禁钓区域信息
      calculateNoFishingAreaInfo() {
        if (!this.noFishingSelectedOverlay) return;

        const path = this.noFishingSelectedOverlay.getPath();
        let coordinates = [];

        // 收集所有顶点
        path.forEach(point => {
          coordinates.push([point.getLng(), point.getLat()]);
        });

        // 保存区域坐标
        this.form.noFishingZone = JSON.stringify(coordinates);
      },

      // 确认禁钓区域选择
      confirmNoFishingMapSelection() {
        if (!this.noFishingSelectedOverlay) {
          this.$message.warning('请先在地图上绘制禁钓区域');
          return;
        }
        this.noFishingMapDialogVisible = false;
      },
      loadTencentMap() {
        return new Promise((resolve, reject) => {
          const checkQQMaps = () => {
            if (window.qq && window.qq.maps && window.qq.maps.LatLng) {
              console.log('地图API加载完成');
              resolve();
              return;
            }
            setTimeout(checkQQMaps, 100);
          };

          // 如果脚本已存在，直接检查
          if (document.querySelector('script[src*="map.qq.com"]')) {
            checkQQMaps();
            return;
          }

          // 创建一个新的script元素
          const script = document.createElement('script');
          script.type = 'text/javascript';
          // 使用callback方式加载地图
          const callback = 'init' + Math.random().toString(36).substr(2, 8);
          window[callback] = () => {
            console.log('地图回调函数执行');
            delete window[callback]; // 清理回调函数
            checkQQMaps();
          };

          script.src =
            `https://map.qq.com/api/js?v=2.exp&key=7WOBZ-7Y6NZ-PG3XQ-7RZ6O-BA4BK-KNBRL&libraries=drawing,geometry&callback=${callback}`;
          script.async = true;
          script.onerror = (error) => {
            console.error('地图加载失败:', error);
            delete window[callback];
            reject(error);
          };

          // 将脚本添加到head中
          document.head.appendChild(script);
        });
      },

      // 打开地图对话框
      async openMapDialog() {
        try {
          // 先加载地图API
          await this.loadTencentMap();

          // 确保API加载完成后再显示对话框
          this.mapDialogVisible = true;

          // 等待DOM更新完成
          await this.$nextTick();

          // 初始化地图
          const mapContainer = document.getElementById('map-container');
          if (!mapContainer) {
            throw new Error('找不到地图容器');
          }

          // 确保地图实例被正确创建
          if (!this.map && window.qq && window.qq.maps) {
            const center = new window.qq.maps.LatLng(39.916527, 116.397128);
            this.map = new window.qq.maps.Map(mapContainer, {
              center: center,
              zoom: 12,
              mapTypeControl: true
            });

            // 初始化绘制工具
            this.drawingManager = new window.qq.maps.drawing.DrawingManager({
              map: this.map,
              drawingMode: window.qq.maps.drawing.OverlayType.POLYGON,
              drawingControl: true,
              drawingControlOptions: {
                position: window.qq.maps.ControlPosition.TOP_CENTER,
                drawingModes: [window.qq.maps.drawing.OverlayType.POLYGON]
              }
            });

            // 监听绘制完成事件
            window.qq.maps.event.addListener(this.drawingManager, 'overlaycomplete', (event) => {
              if (this.selectedOverlay) {
                this.selectedOverlay.setMap(null);
              }
              this.selectedOverlay = event.overlay;
              this.calculateAreaInfo();
            });
          }

          // 触发地图重绘
          if (this.map) {
            this.$nextTick(() => {
              this.map.panTo(this.map.getCenter());
            });
          }

        } catch (error) {
          console.error('地图初始化失败:', error);
          this.$message.error('地图加载失败，请重试');
          this.mapDialogVisible = false;
        }
      },

      // 初始化地图
      async initMap() {
        try {
          const mapContainer = document.getElementById('map-container');
          if (!mapContainer) {
            throw new Error('找不到地图容器');
          }

          if (!window.qq || !window.qq.maps) {
            throw new Error('地图API未加载');
          }

          if (!this.map) {
            const center = new window.qq.maps.LatLng(39.916527, 116.397128);
            this.map = new window.qq.maps.Map(mapContainer, {
              center: center,
              zoom: 12,
              mapTypeControl: true
            });

            // 初始化绘制工具
            this.drawingManager = new window.qq.maps.drawing.DrawingManager({
              map: this.map,
              drawingMode: window.qq.maps.drawing.OverlayType.POLYGON,
              drawingControl: true,
              drawingControlOptions: {
                position: window.qq.maps.ControlPosition.TOP_CENTER,
                drawingModes: [window.qq.maps.drawing.OverlayType.POLYGON]
              }
            });

            window.qq.maps.event.addListener(this.drawingManager, 'overlaycomplete', (event) => {
              if (this.selectedOverlay) {
                this.selectedOverlay.setMap(null);
              }
              this.selectedOverlay = event.overlay;
              this.calculateAreaInfo();
            });
          }
        } catch (error) {
          console.error('地图初始化错误:', error);
          throw error;
        }
      },
      // 计算区域信息
      calculateAreaInfo() {
        if (!this.selectedOverlay) return;

        const path = this.selectedOverlay.getPath();
        let bounds = new qq.maps.LatLngBounds();
        let coordinates = [];

        // 收集所有顶点并计算边界
        path.forEach(point => {
          bounds.extend(point);
          coordinates.push([point.getLng(), point.getLat()]);
        });

        // 计算中心点
        const center = bounds.getCenter();
        this.form.longitude = center.getLng().toFixed(6);
        this.form.latitude = center.getLat().toFixed(6);

        // 保存区域坐标
        this.form.fishingZone = JSON.stringify(coordinates);
        console.log("去获取地址")

      },
      // 确认地图选择
      confirmMapSelection() {
        if (!this.selectedOverlay) {
          this.$message.warning('请先在地图上绘制钓鱼区域');
          return;
        }
        this.mapDialogVisible = false;
      },
      /** 查询水域管理列表 */
      getList() {
        this.loading = true;
        listWater(this.queryParams).then(response => {
          this.waterList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          waterType: null,
          waterName: null,
          locationName: null,
          longitude: null,
          latitude: null,
          catchTotal: null,
          price: null,
          useStatus: null,
          status: null,
          createBy: null,
          crateTime: null,
          updateBy: null,
          updateTime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加水域管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getWater(id).then(response => {
          this.form = response.data;
          if(this.form.protectingFishids){
            this.form.protectingFishids = this.form.protectingFishids.split(",").map(Number);
          }

          /*if(this.form.fishids){
            this.form.fishids = this.form.fishids.split(",").map(Number);
          }*/

          this.open = true;
          this.title = "修改水域管理";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.protectingFishids=this.form.protectingFishids.toString()
            //this.form.fishids=this.form.fishids.toString()
            if (this.form.id != null) {
              updateWater(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addWater(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除水域管理编号为"' + ids + '"的数据项？').then(function() {
          return delWater(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('map/water/export', {
          ...this.queryParams
        }, `water_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
<style scoped>
  .map-container {
    width: 100%;
    height: 500px;
    margin: 10px 0;
  }
</style>
